<!-- 例子： <dictionary v-model="formData.sex" type-code="sex" /> -->
<template>
  <el-select v-model="selectedValue" :placeholder="placeholder" :disabled="disabled" filterable clearable @change="handleChange">
    <el-option v-for="option in options" :key="option.value" :label="option.label" :value="option.value" />
  </el-select>
</template>

<script setup lang="ts">
// 模拟字典类型
import { getDictOptions } from "@/api/dict";

type Change = string | number | undefined;
interface Props {
  typeCode: string;
  modelValue: string | number;
  placeholder: string;
  disabled: boolean;
}
const { typeCode, modelValue, placeholder = "请选择", disabled = false } = defineProps<Props>();

const emits = defineEmits(["update:modelValue"]); // 父组件监听事件，同步子组件值的变化给父组件

const options: Ref<OptionType[]> = ref([]); // 字典下拉数据源

const selectedValue = ref<Change>("");

watch([options, () => modelValue], ([newOptions, newModelValue]) => {
  if (newOptions.length === 0) return; // 下拉数据源加载未完成不回显
  if (newModelValue == undefined) {
    selectedValue.value = undefined;
    return;
  }
  if (typeof newOptions[0].value === "number") {
    selectedValue.value = Number(newModelValue);
  } else if (typeof newOptions[0].value === "string") {
    selectedValue.value = String(newModelValue);
  } else {
    selectedValue.value = newModelValue;
  }
});

const handleChange = (val?: Change) => {
  emits("update:modelValue", val);
};

onBeforeMount(() => {
  // 根据字典类型编码(typeCode)获取字典选项
  getDictOptions(typeCode).then((response: any) => {
    options.value = response.data;
  });
});
</script>
